package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    String PRE_FIX = "ly:cart:uid:";
    /**
     * 添加商品到购物车
     * 操作redis
     * @param cart
     * @return
     */
    public void saveCart(Cart cart, HttpServletRequest request) {

        try{
////        获取用户token
//            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
////       解码payload的内容
//            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
////        获取用户id
//            Long userId = payload.getUserInfo().getId();
            Long userId = UserHolder.getUserId();

            String redisKey = PRE_FIX + userId;

            String hashKey = cart.getSkuId().toString();
//            通过skuid 获取对应的购物车数据
            BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(redisKey);

            String cartJson = boundHashOps.get(hashKey);

//            前端传递的商品数量
            Integer num = cart.getNum();
            if(!StringUtils.isBlank(cartJson)){
                cart = JsonUtils.toBean(cartJson,Cart.class);
//                商品数量的叠加
                cart.setNum(num + cart.getNum());
            }

            redisTemplate.opsForHash().put(redisKey,hashKey, JsonUtils.toString(cart));
        }catch(Exception e){
            e.printStackTrace();
            throw new LyException(ExceptionEnum.CARTS_SAVE_ERROR);
        }

    }

    /**
     * 查询用户的购物车数据
     * @param request
     * @return
     */
    public List<Cart> findCarts(HttpServletRequest request) {
        try{
////        获取用户token
//            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
////       解码payload的内容
//            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
////        获取用户id
//            Long userId = payload.getUserInfo().getId();
            Long userId = UserHolder.getUserId();
            String redisKey = PRE_FIX + userId;
//        查询用户的所有购物车数据
            BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(redisKey);
//        查询rediskey下的所有value
            List<String> cartsJsonList = boundHashOps.values();
            if(CollectionUtils.isEmpty(cartsJsonList)){
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
//        转对象
            List<Cart> cartList = cartsJsonList.stream().map(str -> {
                return JsonUtils.toBean(str, Cart.class);
            }).collect(Collectors.toList());
            return cartList;
        }catch(Exception e){
            e.printStackTrace();
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }


    }

    /**
     * 修改商品数量
     * @param skuId
     * @param num
     * @return
     */
    public void updateCartNum(Long skuId, Integer num) {
//        获取userid
        Long userId = UserHolder.getUserId();
        String redisKey = PRE_FIX + userId;
        String hashKey = skuId.toString();
//        获取skuid对应的购物车信息
        BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(redisKey);
//        获取数据
        String cartJson = boundHashOps.get(hashKey);
//        判断数据是否存在
        if(!StringUtils.isBlank(cartJson)){
            Cart cart = JsonUtils.toBean(cartJson, Cart.class);
            cart.setNum(num);
            boundHashOps.put(hashKey,JsonUtils.toString(cart));
        }
    }

    /**
     * 删除购物车
     * @param skuId
     * @return
     */
    public void deleteCart(Long skuId) {
        Long userId = UserHolder.getUserId();
        String redisKey = PRE_FIX + userId;
        String hashKey = skuId.toString();
        redisTemplate.opsForHash().delete(redisKey,hashKey);
    }

    /**
     * 登陆后的 购物车合并
     * 把未登录的购物车内容提交到服务端
     * @param cartList
     * @return
     */
    public void saveCartBatch(List<Cart> cartList) {
//        获取用户信息
        Long userId = UserHolder.getUserId();
//        redisKey
        String redisKey = PRE_FIX + userId;
//        获取用户的搜索购物车内容
        BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(redisKey);
        List<String> cartJsonList = boundHashOps.values();

        List<Cart> cacheCartList = cartJsonList.stream().map(str -> {
            return JsonUtils.toBean(str, Cart.class);
        }).collect(Collectors.toList());

        for (Cart cart1 : cartList) {
            Long skuId1 = cart1.getSkuId();
//            获取用户传递的数量
            for (Cart cart : cacheCartList) {
                Long skuId = cart.getSkuId();
                if(skuId.longValue() == skuId1.longValue()){
//                    说明redis中存在，叠加数量
                    cart1.setNum(cart1.getNum() + cart.getNum());
                }
            }
//            保存到redis
            boundHashOps.put(cart1.getSkuId().toString(),JsonUtils.toString(cart1));

        }


    }
}
